import React, { useEffect, useState } from 'react';
import { Switch } from 'antd';
import ChooseGroup, { CheckboxValueType } from '../ChooseGroup';
import Message from '@/utils/message';
import ChooseRest from '../ChooseRest';
import { appoint, setOtherWork } from '@/utils/lib';
import { setCheckInGroups } from '@/store/reducers/login';
import { useDispatch, useSelector } from 'react-redux';
import { setAgentStatus } from '@/store/reducers/agent';
import { useMenuContext, TabsProps } from '../Context/MenuContext';
import { judgeChief } from '@/api';
import { useTranslation } from 'react-i18next';
import AgentService, { IEvent } from '@/modules/Agent';
import styled from '@emotion/styled';

interface AgentStatusProps {
	label?: string;
}

interface Respone {
	code: number | string;
	message: string;
}

const AgentStatusSwitch = styled(Switch)`
	cursor: ${(props: { afterwork: string }) => (props.afterwork === 'true' ? 'no-drop' : '')};
`;

const AgentStatus = (props: AgentStatusProps) => {
	const { t } = useTranslation();
	const dispatch = useDispatch();
	const { setLoading } = useMenuContext();
	const { login, session, agent, networkStatus, configure } = useSelector((state: any) => state);
	const { label = t('agent-status') } = props;
	// 签入分组弹窗
	const [showCheckeGroup, setShowCheckeGroup] = useState(false);
	// 选择小休弹窗
	const [showChooseRest, setShowChooseRest] = useState<boolean>(false);

	//就绪
	const changeSwitchReady = async () => {
		if (AgentService.agentStatus.afterWork) return;
		// AMS重连中 在重连中，点击签入、就绪，toast提示“操作失败”
		if (['reconnect_failed', 'reconnecting', 'offline'].includes(networkStatus.amsStatus)) {
			Message.warning(t('action-failed'));
			return;
		}
		if (session.sessionId) {
			Message.warning(t('not-support-under-session'));
			return;
		}
		setLoading(true);
		if (!AgentService.agentStatus.ready) {
			try {
				const data = await AgentService.agentReady();
				console.log(data);

				if (data.code == 200) {
					dispatch(setAgentStatus({ key: 'ready', value: true }));
					dispatch(setAgentStatus({ key: 'otherWork', value: false }));
					setLoading(false);
				} else {
					setLoading(false);
				}
			} catch (error) {
				dispatch(setAgentStatus({ key: 'ready', value: false }));
				console.log(error, 'ready error');
				setLoading(false);
			}
		} else {
			try {
				const data = await AgentService.agentUnReady();
				if (data.code == 200) {
					dispatch(setAgentStatus({ key: 'ready', value: false }));
					setLoading(false);
				} else {
					setLoading(false);
				}
			} catch (error) {
				console.log(error, 'unready error');
				setLoading(false);
			}
		}
	};
	//签入
	const changeSwitchCheckIn = () => {
		if (AgentService.agentStatus.afterWork) return;
		// AMS重连中 在重连中，点击签入、就绪，toast提示“操作失败”
		if (['reconnect_failed', 'reconnecting', 'offline'].includes(networkStatus.amsStatus)) {
			Message.warning(t('action-failed'));
			return;
		}
		if (!AgentService.agentStatus.checkIn) {
			setShowCheckeGroup(true);
		} else {
			checkOutGroups();
		}
	};

	//打开设置小休弹窗
	const changeOtherWork = () => {
		if (AgentService.agentStatus.afterWork) return;
		if (AgentService.agentStatus.otherWork) return;
		setShowChooseRest(true);
	};

	const getOtherWork = () => {
		if ((AgentService.sessionId && AgentService.agentStatus.otherWork) || (!AgentService.sessionId && AgentService.agentStatus.otherWork && AgentService.agentStatus.afterWork)) {
			return t('booked-break');
		}
		if (AgentService.sessionId && !AgentService.agentStatus.otherWork) {
			return t('book-break');
		}
		if (!AgentService.sessionId && AgentService.agentStatus.otherWork && !AgentService.agentStatus.afterWork) {
			return t('taking-break');
		}
		if (!AgentService.sessionId && !AgentService.agentStatus.otherWork) {
			return t('short-break');
		}
	};

	// 签入分组
	const checkedGroup = async (values: any) => {
		setLoading(true);
		setShowCheckeGroup(false);
		try {
			const data = await AgentService.checkinSystem(values);
			if (data?.code === 200) {
				dispatch(setCheckInGroups(values));
				dispatch(setAgentStatus({ key: 'checkIn', value: true }));
				setLoading(false);
			} else {
				setLoading(false);
			}
		} catch (error) {
			console.log('checkin error', error);
			setLoading(false);
		}
	};

	//签出分组
	const checkOutGroups = async () => {
		if (AgentService.sessionId) {
			Message.warning(t('not-support-under-session'));
			return;
		}
		setLoading(true);
		try {
			const data = await AgentService.checkoutSystem();
			if (data?.code === 200) {
				dispatch(setAgentStatus({ key: 'checkIn', value: false }));
				setLoading(false);
			} else {
				setLoading(false);
			}
		} catch (error) {
			console.log(error, 'checkout groups');
			setLoading(false);
		}
	};

	//小休
	const onSubmitRest = async (data: string) => {
		if (!AgentService.agentStatus.otherWork) {
			if (session.sessionId) {
				let reason = { appointState: 'otherWork', reason: data };
				try {
					const resp = (await appoint(reason)) as Respone;
					if (resp.code === 200) {
						setShowChooseRest(false);
						dispatch(setAgentStatus({ key: 'otherWork', value: true }));
						dispatch(setAgentStatus({ key: 'ready', value: false }));
						AgentService.setAgentStatus({ ...AgentService.agentStatus, otherWork: true, ready: false });
					}
				} catch (error) {
					console.log(error, 'appoint error');
				}
			} else {
				let reason = {
					reason: data
				};
				try {
					const resp = (await setOtherWork(reason)) as Respone;
					if (resp.code === 200) {
						setShowChooseRest(false);
						dispatch(setAgentStatus({ key: 'otherWork', value: true }));
						dispatch(setAgentStatus({ key: 'ready', value: false }));
						AgentService.setAgentStatus({ ...AgentService.agentStatus, otherWork: true, ready: false });
					}
				} catch (error) {
					console.log(error, 'setOtherWorkReason error');
				}
			}
		}
	};

	useEffect(() => {
		AgentService.addEventListener(resp => {
			if (resp.event === IEvent.SET_AGENT_STATUS) {
				getOtherWork();
			}
		});
		return () => {
			AgentService.removeEventListener();
		};
	}, []);

	return (
		<div className="agent-status-box">
			<div className="agent-status-label">{label}</div>
			<div className="agent-status-switch-box">
				<div className="status-box">
					<span className="logged">{AgentService.agentStatus.checkIn ? t('checked-in') : t('not-checked-in')}</span>
					{/* <Switch checked={agent.status.checkIn} onChange={changeSwitchCheckIn} status={checkInStatus} /> */}
					<AgentStatusSwitch afterwork={AgentService.agentStatus.afterWork.toString()} checked={AgentService.agentStatus.checkIn} onChange={changeSwitchCheckIn} />
				</div>
				<div className="status-box">
					<span className="logged">{AgentService.agentStatus.ready ? t('ready') : t('not-ready')}</span>
					{/* <Switch checked={agent.status.ready} onChange={changeSwitchReady} status={readyStatus} /> */}
					<AgentStatusSwitch afterwork={AgentService.agentStatus.afterWork.toString()} checked={AgentService.agentStatus.ready} onChange={changeSwitchReady} />
				</div>
				<span
					style={{ display: !AgentService.agentStatus.ready && !AgentService.agentStatus.otherWork ? 'none' : 'block', cursor: AgentService.agentStatus.afterWork ? 'no-drop' : '' }}
					className={AgentService.agentStatus.otherWork ? 'active-agent-status' : 'agent-status-txt'}
					onClick={changeOtherWork}
				>
					{getOtherWork()}
				</span>
			</div>
			{/* 签入分组 */}
			<ChooseGroup
				visible={showCheckeGroup}
				onSubmit={checkedGroup}
				onClose={() => {
					setShowCheckeGroup(false);
				}}
			></ChooseGroup>
			{/* 选择小休 */}
			<ChooseRest
				visible={showChooseRest}
				onClose={() => {
					setShowChooseRest(false);
				}}
				onOk={onSubmitRest}
			></ChooseRest>
		</div>
	);
};

export default AgentStatus;
